<template>
  <view class="xen-attachment-upload">
    <!-- 文件数量统计 -->
    <view v-if="attachments.length > 0 || maxCount > 1" class="file-count">
      <text class="count-label">最多选择{{ maxCount }}个文件</text>
      <text class="count-text">{{ attachments.length }}/{{ maxCount }}</text>
    </view>

    <!-- 附件列表和上传按钮 -->
    <view class="attachment-list">
      <!-- 已上传的附件 -->
      <view
        v-for="(attachment, index) in attachments"
        :key="attachment.id || index"
        class="attachment-item"
        @tap="handleAttachmentClick(attachment)"
      >
        <!-- 缩略图区域 -->
        <view class="thumbnail-container">
          <!-- 图片缩略图 -->
          <image
            v-if="isImage(attachment)"
            :src="attachment.url || attachment.path"
            class="thumbnail-image"
            mode="aspectFill"
            @error="handleImageError(attachment, index)"
          />
          <!-- 文件图标 -->
          <view v-else class="file-icon-container">
            <uni-icons
              :type="getFileIcon(attachment) as any"
              size="32"
              :color="getFileIconColor(attachment)"
            />
            <text class="preview-hint">点击预览</text>
          </view>

          <!-- 删除按钮 -->
          <view class="delete-btn" @tap.stop="handleDelete(attachment, index)">
            <uni-icons type="clear" size="24" color="#666" />
          </view>
        </view>

        <!-- 文件信息 -->
        <view class="attachment-info">
          <text class="file-name">{{ getFileName(attachment) }}</text>
        </view>
      </view>

      <!-- 上传按钮 - 放在文件列表末端 -->
      <view
        v-if="canAddMore"
        class="attachment-item upload-item"
        @tap="handleUpload"
      >
        <view class="upload-trigger">
          <uni-icons type="plus" size="24" color="#7881de" />
          <text class="upload-text">{{ placeholder }}</text>
        </view>
      </view>
    </view>

    <!-- 提示信息 -->
    <view v-if="tips" class="upload-tips">
      <text class="tips-text">{{ tips }}</text>
    </view>

    <!-- 使用原生文件选择，不显示uni-file-picker的界面 -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import commonApi from "../api/common";

// 附件数据接口
export interface AttachmentItem {
  id?: string;
  fileID?: string;
  name: string;
  url?: string;
  path?: string;
  size?: number;
  extname?: string;
  type?: string;
}

// 组件属性
interface Props {
  modelValue: AttachmentItem[];
  placeholder?: string;
  accept?: "image" | "all" | "video" | "file";
  maxCount?: number;
  maxSize?: number; // MB
  tips?: string;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  placeholder: "添加附件",
  accept: "all",
  maxCount: 10,
  maxSize: 10,
  tips: "",
  disabled: false,
});

// 事件定义
const emit = defineEmits<{
  "update:modelValue": [value: AttachmentItem[]];
  upload: [files: any[]];
  delete: [attachment: AttachmentItem, index: number];
  preview: [attachment: AttachmentItem];
}>();

// 计算属性
const attachments = computed(() => props.modelValue || []);

const canAddMore = computed(() => {
  return !props.disabled && attachments.value.length < props.maxCount;
});

const remainingCount = computed(() => {
  return props.maxCount - attachments.value.length;
});

// 判断是否为图片
const isImage = (attachment: AttachmentItem): boolean => {
  const imageExts = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"];
  const extname =
    attachment.extname?.toLowerCase() ||
    attachment.name?.split(".").pop()?.toLowerCase() ||
    "";
  
  return imageExts.includes(extname);
};

// 获取文件图标 - 统一使用wallet图标
const getFileIcon = (attachment: AttachmentItem): string => {
  return "wallet";
};

// 获取文件图标颜色 - 统一使用默认颜色
const getFileIconColor = (attachment: AttachmentItem): string => {
  return "#7881de";
};

// 获取文件名 - 简单显示，不主动获取
const getFileName = (attachment: AttachmentItem): string => {
  let name = attachment.name || "未知文件";

  // 如果文件名太长，进行截断
  if (name.length > 15) {
    const ext = name.split(".").pop() || "";
    const nameWithoutExt = name.substring(0, name.lastIndexOf("."));
    const truncatedName = nameWithoutExt.substring(0, 10) + "...";
    name = ext ? `${truncatedName}.${ext}` : truncatedName;
  }
  return name;
};

// 文件大小显示已移除

// 处理上传 - 使用正确的文件选择API
const handleUpload = () => {
  if (props.disabled || !canAddMore.value) return;

  // 根据accept类型选择合适的API
  if (props.accept === "image") {
    // 选择图片
    uni.chooseImage({
      count: remainingCount.value,
      sizeType: ["compressed", "original"],
      sourceType: ["album", "camera"],
      success: (res: any) => {
        const tempFiles = (res.tempFilePaths || []).map(
          (path: string, index: number) => ({
            path: path,
            tempFilePath: path,
            size: res.tempFiles?.[index]?.size || 0,
            name: `image_${Date.now()}_${index}.jpg`,
            extname: "jpg",
          }),
        );
        handleFileSelect({ tempFiles });
      },
      fail: (err) => {
        console.error("图片选择失败:", err);
        uni.showToast({
          title: "图片选择失败",
          icon: "none",
        });
      },
    });
  } else {
    // 选择文件（包括图片和其他文件）
    uni.chooseMessageFile({
      count: remainingCount.value,
      type: "all", // 'all' | 'video' | 'image' | 'file'
      success: (res: any) => {
        const tempFiles = (res.tempFiles || []).map((file: any) => ({
          path: file.path,
          tempFilePath: file.path,
          size: file.size,
          name: file.name,
          extname: file.name.split(".").pop() || "",
          type: file.type,
        }));
        handleFileSelect({ tempFiles });
      },
      fail: (err) => {
        console.error("取消选择:", err);
        uni.showToast({
          title: "取消选择",
          icon: "none",
        });
      },
    });
  }
};

// 处理文件选择
const handleFileSelect = (event: any) => {
  const files = event.tempFiles || [];
  if (files.length === 0) return;

  // 检查文件大小
  const oversizeFiles = files.filter((file: any) => {
    const sizeInMB = (file.size || 0) / (1024 * 1024);
    return sizeInMB > props.maxSize;
  });

  if (oversizeFiles.length > 0) {
    uni.showToast({
      title: `文件大小不能超过${props.maxSize}MB`,
      icon: "none",
    });
    return;
  }

  // 触发上传事件
  emit("upload", files);
};

// 预览文件的统一方法
const previewFile = async (fileId: string, fileName?: string) => {
  try {
    uni.showLoading({
      title: "加载中...",
    });

    const tempFilePath = await new Promise<string>((resolve, reject) => {
      const downloadUrl = `${
        import.meta.env.VITE_BASE_URL
      }/api/_file/DownloadFile/${fileId}`;

      uni.downloadFile({
        url: downloadUrl,
        header: {
          Authorization: uni.getStorageSync("token")
            ? `Bearer ${uni.getStorageSync("token")}`
            : "",
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(new Error(`下载失败，状态码：${res.statusCode}`));
          }
        },
        fail: reject,
      });
    });

    // 预览文档
    uni.openDocument({
      filePath: tempFilePath,
      showMenu: true, // 显示菜单，允许用户保存等操作
      success: () => {
        console.log("文件预览成功");
        uni.showToast({
          title: "文件加载成功",
          icon: "success",
        });
      },
      fail: (err) => {
        console.error("文件预览失败:", err);
        uni.showToast({
          title: "文件预览失败",
          icon: "none",
        });
      },
    });
  } catch (error) {
    console.error("文件下载失败:", error);
    uni.showToast({
      title: "文件下载失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 处理附件点击
const handleAttachmentClick = (attachment: AttachmentItem) => {
  if (isImage(attachment)) {
    // 图片预览
    const imageUrl = attachment.url || attachment.path || "";
    
    if (imageUrl) {
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl,
      });
    } else {
      uni.showToast({
        title: "图片URL不存在",
        icon: "none",
      });
    }
  } else {
    // 文件预览 - 使用统一的预览方法
    const fileId = attachment.fileID || attachment.id;
    
    if (fileId) {
      previewFile(fileId, attachment.name);
    } else {
      uni.showToast({
        title: "文件ID不存在",
        icon: "none",
      });
    }
  }

  emit("preview", attachment);
};

// 处理删除
const handleDelete = (attachment: AttachmentItem, index: number) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这个附件吗？",
    success: (res) => {
      if (res.confirm) {
        const newAttachments = [...attachments.value];
        newAttachments.splice(index, 1);
        emit("update:modelValue", newAttachments);
        emit("delete", attachment, index);

        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
      }
    },
  });
};

// 处理图片加载错误
const handleImageError = (attachment: AttachmentItem, index: number) => {
  console.warn("图片加载失败:", attachment);
  // 可以在这里设置默认图片或者显示错误状态
};
</script>

<style lang="scss" scoped>
.xen-attachment-upload {
  width: 100%;

  .file-count {
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .count-label {
      font-size: 12px;
      color: #999;
    }

    .count-text {
      font-size: 12px;
      color: #999;
    }
  }

  .attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 12px;

    .attachment-item {
      position: relative;
      width: 80px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .thumbnail-container {
        position: relative;
        width: 80px;
        height: 80px;
        border-radius: 8px;
        overflow: hidden;
        background: #f5f5f5;
        border: 1px solid #e0e0e0;

        .thumbnail-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .file-icon-container {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: #fafafa;
          gap: 4px;

          .preview-hint {
            font-size: 10px;
            color: #999;
            line-height: 1;
          }
        }

        .delete-btn {
          position: absolute;
          top: 2px;
          right: 2px;
          width: 18px;
          height: 18px;
          border-radius: 50%;
          // background: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1;
          box-sizing: border-box;
        }
      }

      .attachment-info {
        width: 100%;
        margin-top: 4px;
        text-align: center;

        .file-name {
          display: block;
          font-size: 12px;
          color: #333;
          line-height: 1.2;
          word-break: break-all;
        }
      }

      // 上传按钮项样式
      &.upload-item {
        .upload-trigger {
          width: 80px;
          height: 80px;
          border: 2px dashed #d9d9d9;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: #fafafa;
          transition: all 0.3s ease;

          &:active {
            border-color: #7881de;
            background: #f0f2ff;
          }

          .upload-text {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
            text-align: center;
            line-height: 1.2;
          }
        }
      }
    }
  }

  .upload-tips {
    margin-top: 8px;
    padding: 8px 12px;
    background: #f0f8ff;
    border-radius: 4px;
    border-left: 3px solid #1890ff;

    .tips-text {
      font-size: 12px;
      color: #666;
      line-height: 1.4;
    }
  }
}
</style>
